/**
 * 
 */
package soa.security.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.derby.tools.sysinfo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.CollectionUtils;

import soa.security.domain.Account;
import soa.security.mgr.service.AccountMgrService;

/**
 * @author Cre.Gu
 *
 */
public class SoaCasRealm extends CasRealm {

	@Resource
	protected AccountMgrService accountMgrService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		SimpleAuthenticationInfo sai = (SimpleAuthenticationInfo) super
				.doGetAuthenticationInfo(token);
		String userId = (String) sai.getPrincipals().getPrimaryPrincipal();
		
		try {
			System.out.println("userId = " + userId);
			System.out.println("userId = " + new String(userId.getBytes("GBK"), "utf-8"));
			Account account = accountMgrService.findByUid(userId);
			if (account == null)
				return null;

			if (account.isDisable())
				throw new AuthenticationException("登录失败");

			 Map<String, Object> attributes=new HashMap<String, Object>();
			List<Object> principals = CollectionUtils.asList(account.getDn()
					.toString(),attributes);
			PrincipalCollection principalCollection = new SimplePrincipalCollection(
					principals, getName());
			return new SimpleAuthenticationInfo(principalCollection,
					sai.getCredentials());

		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new AuthenticationException("登录失败");
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return super.doGetAuthorizationInfo(principals);
	}

}
